package com.ego.admin.oauth;

import com.ego.admin.po.SysAdmin;
import com.ego.admin.po.SysAdminToken;
import com.ego.admin.service.SysAdminService;
import com.ego.admin.service.SysAdminTokenService;
import com.ego.admin.service.SysMenuService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @program: ego
 * @description: 自定义Realm
 * @author: KamTang
 * @create: 2022-11-13 09:13
 **/
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysAdminTokenService sysAdminTokenService;

    @Autowired
    private SysAdminService sysAdminService;

    @Autowired
    private SysMenuService menuService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OauthToken;
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysAdmin admin = (SysAdmin) principalCollection.getPrimaryPrincipal();
        Long userId = admin.getUserId();

        // 用户权限列表
        Set<String> permissions = menuService.getUserPermissions(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken token
     * @return AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取token
        String token = (String) authenticationToken.getPrincipal();
        SysAdminToken tokenEntity = sysAdminTokenService.queryByToken(token);
        if (tokenEntity == null) {
            throw new IncorrectCredentialsException("token为空，请重新登录。");
        }
        // 获取的tokenEntity失效
        if (tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token已失效，请重新登录。");
        }
        // 根据id查询admin
        SysAdmin admin = sysAdminService.getById(tokenEntity.getUserId());
        return new SimpleAuthenticationInfo(admin, token, getName());
    }


}
